package com.wokeMy.view.util;

import android.app.ActivityManager;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.othershe.nicedialog.NiceDialog;
import com.zhongcai.online.R;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2017/12/7 0007.
 */
public class Util {
    /**
     * Glid Option
     * @param isCircle  是否圆形
     * @return
     */

    public static RequestOptions getGlideOptions (boolean isCircle){
        RequestOptions requestOptions=new RequestOptions();
        requestOptions.placeholder(R.mipmap.icn__launch_oem)
                .error(R.mipmap.icn__launch_oem)
                .fallback(R.mipmap.icn__launch_oem)
                .diskCacheStrategy(DiskCacheStrategy.NONE) //缓存策略
                .centerCrop();
        if (isCircle){
            requestOptions.transform(new CircleCrop());
        }
        return requestOptions;
    }
    /**
     *  得到ip地址
     * @param context
     * @return
     */
    public static String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }

            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null;
    }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    /**
     * niceDialog 加载弹框
     * @return
     */
    public static NiceDialog lodingDialog() {

        NiceDialog niceDialog  =NiceDialog.init();
        niceDialog
                .setLayoutId(R.layout.loading_layout)
                .setWidth(100)
                .setHeight(100)
                .setDimAmount(0);

        return niceDialog;
    }

    public static Dialog createLoadingDialog(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.dialog_loading, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v
                .findViewById(R.id.dialog_loading_view);// 加载布局
        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
        tipTextView.setText("加载中...");// 设置加载信息

        Dialog loadingDialog = new Dialog(context, R.style.MyDialogStyle);// 创建自定义样式dialog
        loadingDialog.setCancelable(true); // 是否可以按“返回键”消失
        loadingDialog.setCanceledOnTouchOutside(false); // 点击加载框以外的区域
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
        /**
         *将显示Dialog的方法封装在这里面
         */
        Window window = loadingDialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setGravity(Gravity.CENTER);
        window.setAttributes(lp);
        window.setWindowAnimations(R.style.PopWindowAnimStyle);
        loadingDialog.show();

        return loadingDialog;
    }
    public static Dialog createLoadingDialog(Context context,String string) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.dialog_loading, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v
                .findViewById(R.id.dialog_loading_view);// 加载布局
        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
        tipTextView.setText(string);// 设置加载信息

        Dialog loadingDialog = new Dialog(context, R.style.MyDialogStyle);// 创建自定义样式dialog
        loadingDialog.setCancelable(true); // 是否可以按“返回键”消失
        loadingDialog.setCanceledOnTouchOutside(false); // 点击加载框以外的区域
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
        /**
         *将显示Dialog的方法封装在这里面
         */
        Window window = loadingDialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setGravity(Gravity.CENTER);
        window.setAttributes(lp);
        window.setWindowAnimations(R.style.PopWindowAnimStyle);
        loadingDialog.show();

        return loadingDialog;
    }
    /**
     *  腾付通 加载过慢
     * @param context
     * @return
     */
    public static Dialog createLoadingDialogTft(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.dialog_loading, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v
                .findViewById(R.id.dialog_loading_view);// 加载布局
        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
        tipTextView.setText("本通道请求时间较长，请耐心等待!");// 设置加载信息

        Dialog loadingDialog = new Dialog(context, R.style.MyDialogStyle);// 创建自定义样式dialog
        loadingDialog.setCancelable(true); // 是否可以按“返回键”消失
        loadingDialog.setCanceledOnTouchOutside(false); // 点击加载框以外的区域
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
        /**
         *将显示Dialog的方法封装在这里面
         */
        Window window = loadingDialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setGravity(Gravity.CENTER);
        window.setAttributes(lp);
        window.setWindowAnimations(R.style.PopWindowAnimStyle);
        loadingDialog.show();

        return loadingDialog;
    }
    /**
     * 关闭dialog
     *
     * http://blog.csdn.net/qq_21376985
     *
     * @param mDialogUtils
     */
    public static void closeDialog(Dialog mDialogUtils) {
        if (mDialogUtils != null && mDialogUtils.isShowing()) {
            mDialogUtils.dismiss();
        }
    }

    /**
     * 得到 sHA1
     * @param context
     * @return
     */
    public static String sHA1(Context context) {
        try {
            PackageInfo info = null;
            try {
                info = context.getPackageManager().getPackageInfo(
                        context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
                String result = hexString.toString();
                return result.substring(0, result.length()-1);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 变两位小数
     * @param price_CNY
     * @return
     */
    public static String twoString(String price_CNY){
//      return s.substring(0,s.indexOf(".")+3) ;
        Double cny = Double.parseDouble(price_CNY);//转换成Double
        DecimalFormat df = new DecimalFormat("0.00");//格式化
        String CNY = df.format(cny);
        return  CNY;
    }
    /**
     * 银行卡号处理
     * @param s
     * @return
     */
    public static String bankCard(String s){
      return s.substring(0, 4)+"    "+"***"+"    "+"***"+"    "+"***"+"    "+s.substring(s.length()-3,s.length());
    }
    /**
     * 开奖期号处理 (双色球开奖)
     * @param s
     * @return
     */
    public static String dealtIssue(String s){
        if (s.contains(",")){
            s=s.replace(","," ");
            Log.e("dealtIssue","进来了"+s);
        }
        String qian=s.substring(0,s.length()-2);
        String red=s.substring(s.length()-2,s.length());

        String str=qian+"| <font color='#1a98e1'> "+ red+"</font>";
      return str;
    }
    /**
     * 开奖期号处理 (大乐透)
     * @param s
     * @return
     */
    public static String dealtIssueDuo(String s,int geshu){
        if (s.contains(",")){
            s=s.replace(","," ");
            Log.e("dealtIssue","进来了"+s);
        }
        String qian=s.substring(0,s.length()-2*geshu-1);
        String red=s.substring(s.length()-(2*geshu)-1,s.length());

        String str=qian+"| <font color='#1a98e1'> "+ red+"</font>";
      return str;
    }
    /**
     * 开奖期号处理 (双色球开奖公告)
     * @param s 06,08,13,15,22,33,06"
     * @return
     */
    public static ArrayList<String>  dealtIssueGg(String s){
        ArrayList<String> ball=new ArrayList<>();
            String[] split = s.split(",");
            for (int i = 0; i < split.length; i++) {
                ball.add(split[i]);
            }
      return ball;
    }
    /**
     * 投注详情期号处理
     * @param s 272324162528|06
     * @return
     */
    public static ArrayList<String>  dealtIssudetial(String s){
        ArrayList<String> ball=new ArrayList<>();
        if (s.contains("|")){
            s=s.replace("|","");
            Log.e("dealtIssudetial",s);
            for (int i = 0; i < s.length(); i+=2) {
                String substring = s.substring(i, i + 2);
                Log.e("dealtIssudetial",substring);
                ball.add(substring);
            }
        }else {
            ball.add(s);
        }

      return ball;
    }
    /**
     * 投注球view String
     * @param
     * @return
     */
    public static String getViewString(ArrayList<String> blueBall,ArrayList<String> redBall){
        StringBuffer stringBuffer =new StringBuffer();
        StringBuffer sbRed =new StringBuffer();
        for (int i = 0; i <blueBall.size(); i++) {
            String buleball;
            int s = Integer.valueOf(blueBall.get(i)) + 1;
            if (s<10){
                buleball="0"+s+" ";
            }else {
                buleball=s+" ";
            }
            stringBuffer.append(buleball);
        }
        for (int i = 0; i < redBall.size(); i++) {
            String buleball;
            int s = Integer.valueOf(redBall.get(i)) + 1;
            if (s < 10) {
                buleball = "0" + s+" ";
            } else {
                buleball = s + " ";
            }
            sbRed.append(buleball);
        }
        String str = stringBuffer.toString() + "<font color='#1a98e1'> " + sbRed.toString() + "</font>";
        return str;
 }
    public static  ArrayList<String> ballSort(ArrayList<String> ball){
        Collections.sort(ball, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {

                return new Double((String) o1).compareTo(new Double((String) o2));

            }
        });
//        for (int i = 0; i < ball.size(); i++) {
//            int s = Integer.valueOf(ball.get(i));
//            if (s < 10) {
//                ball.set(i,0+"s");
//            }
//        }
        return ball;
    }
    /**
     * 得到 getProcessName
     * @param cxt
     * @return
     */
    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

    /**
     *  判断在素组中是否有这个元素
     * @param strings
     * @param s
     * @return
     */
    public static boolean isDouble(ArrayList<String> strings,String s){

        for (int i = 0; i < strings.size(); i++) {
            if (strings.get(i).equals(s)){
                return true;
            }

        }
        return false;
    }
    /**
     *  多次随机[0, Length-1] 的数
     * @param length  随机范围
     * @param chiShu  随机次数
     * @return
     */
    public static ArrayList<String> createRandom(int length,int chiShu) {
        ArrayList<String> random=new ArrayList<>();
        for (int i = 0; i < chiShu; i++) {
            int a=0;
            boolean yY=true;
            while (yY) {
                yY=false;
                a=(int)(0+Math.random()*(length));
                //        		 Log.e("aaa", a+"");
                for (int j = 0; j < random.size(); j++) {
                    if (a==Integer.valueOf(random.get(j))) {
                        yY=true;
                    }
                }
                if (yY==false) {
                    random.add(a+"");
                    break;
                }
            }

        }

        return random;
    }

    /**
     * 判断数组里面有没有这个数
     * @param num 这个数
     * @param list 数组
     * @return
     */
    public  static boolean  haveNum(int num,ArrayList<String> list){

        for (int j = 0; j < list.size(); j++) {
            if (num==Integer.valueOf(list.get(j))) {
                return  true;
            }
        }
        return  false;
    }

    /**
     * 计算排列数，即A(n, m) = n!/(n-m)!
     *  n 个里面选 m 个  不可以重复
     * @param n
     * @param m
     * @return
     */
    public static long arrangement(int n, int m) {
        return (n >= m) ? factorial(n) / factorial(n - m) : 0;
    }

    /**
     * 计算组合数，即C(n, m) = n!/((n-m)! * m!)
     * n 个里面选 m 个  可以重复
     * @param n
     * @param m
     * @return
     */
    public static long combination(int n, int m) {
        return (n >= m) ? factorial(n) / factorial(n - m) / factorial(m) : 0;
    }

    /**
     * 计算阶乘数，即n! = n * (n-1) * ... * 2 * 1
     * @param n
     * @return
     */
    private static long factorial(int n) {
        return (n > 1) ? n * factorial(n - 1) : 1;
    }
    /**
     * 判断对象或对象数组中每一个对象是否为空: 对象为null，字符序列长度为0，集合类、Map为empty
     *
     * @param obj
     * @return
     */
    public static boolean isNullOrEmpty(Object obj) {
        if (obj == null)
            return true;

        if (obj instanceof CharSequence)
            return ((CharSequence) obj).length() == 0;

        if (obj instanceof Collection)
            return ((Collection) obj).isEmpty();

        if (obj instanceof Map)
            return ((Map) obj).isEmpty();

        if (obj instanceof Object[]) {
            Object[] object = (Object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (int i = 0; i < object.length; i++) {
                if (!isNullOrEmpty(object[i])) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }
        return false;
    }

    public static String getStrTi(String cc_time) {
        String re_StrTime = null;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // cc_time=1291778220
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;

    }

    public static Set<Integer> filter(List<Integer> array, int type){
        Set<Integer> _array = new HashSet<Integer>();
        Map<Integer, Integer> mapper = new HashMap<>();
        int subLen = array.size()/2;
        for(int i=0; i<array.size(); i++){
            int num = array.get(i);
            if(type%2==0){// 大
                if(i>=subLen) _array.add(num);
            }
            if(type%3==0){// 小
                if(i<subLen) _array.add(num);
            }
            mapper.put(num, i);
        }
        if(_array.size()==0) _array = new HashSet<Integer>(array);
        Set<Integer> _array2 = new HashSet<Integer>();
        for (Integer _num : _array) {
            if(type%5==0){// 单
                if(_num%2==1) _array2.add(_num);
            }
            if(type%7==0){// 双
                if(_num%2==0) _array2.add(_num);
            }
        }
        Set<Integer> array3 = new HashSet<Integer>();
        if(_array2.size()==0){
            for(Integer value: _array){
                array3.add(mapper.get(value));
            }
        }else{
            for(Integer value: _array2){
                array3.add(mapper.get(value));
            }
        }
        return array3;
    }
}
